﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace BCDEditUI
{
    public class BcdEdit
    {
        #region Add VHD

        public static string AddVhd(string filename, string name)
        {
            if (!File.Exists(filename))
            {
                return "File does not exist.";
            }
            if (string.IsNullOrEmpty(name))
            {
                return "Enter a name.";
            }

            filename = Helper.ParseFileName(filename);
            if (string.IsNullOrEmpty(filename))
            {
                return "Vhd should be on a local disk.";
            }

            string totalOutput = "";
            string output;

            if (!ProcessStart("bcdedit", @"/copy {current} /d """ + name + @"""", out output))
            {
                return output;
            }

            if (string.IsNullOrEmpty(output))
            {
                return "Output missing";
            }
            string guid = Helper.FindGuid(output);
            if (string.IsNullOrEmpty(guid))
            {
                return "Guid not found.";
            }

            if (!ProcessStart("bcdedit", string.Format(@"/set {0} osdevice vhd={1}", guid, filename), out output))
            {
                return output;
            }
            totalOutput += output;

            if (!ProcessStart("bcdedit", string.Format(@"/set {0} detecthal on", guid), out output))
            {
                return output;
            }
            totalOutput += output;

            totalOutput += "Finished.";
            return totalOutput;
        }

        private static bool ProcessStart(string fileName, string arguments, out string output)
        {
            ProcessStartInfo psi = new ProcessStartInfo(fileName, arguments);
            psi.RedirectStandardError = true;
            psi.RedirectStandardOutput = true;
            psi.UseShellExecute = false;
            psi.WindowStyle = ProcessWindowStyle.Hidden;

            Process p = Process.Start(psi);

            string errorText = p.StandardError.ReadToEnd();
            if (!string.IsNullOrEmpty(errorText))
            {
                output = errorText;
                return false;
            }

            output = p.StandardOutput.ReadToEnd();
            return true;
        }
 
        #endregion

    }
}
